<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>事件分类管理</h3>
          <el-button type="primary" @click="showCreateCategoryDialog">新建分类</el-button>
        </div>
      </template>
      
      <el-table :data="categoriesWithCount" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="分类名称" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="eventCount" label="事件数量" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="220">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="editCategory(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="confirmDeleteCategory(row.id)" :disabled="row.eventCount > 0">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 创建/编辑分类弹窗 -->
    <el-dialog
      v-model="categoryDialogVisible"
      :title="isEditing ? '编辑分类' : '新建分类'"
      width="500px"
    >
      <el-form :model="categoryForm" label-width="80px" ref="categoryFormRef" :rules="categoryRules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="categoryForm.name" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="categoryForm.description" type="textarea" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="categoryDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveCategory" :loading="submitting">
            {{ isEditing ? '保存' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'

const store = useStore()

const loading = ref(false)
const submitting = ref(false)
const categoryDialogVisible = ref(false)
const isEditing = ref(false)
const categoryFormRef = ref(null)

const categoryForm = ref({
  id: '',
  name: '',
  description: ''
})

const categoryRules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
}

const categoriesWithCount = computed(() => {
  return store.state.categories.map(category => {
    const eventCount = store.state.events.filter(event => event.categoryId === category.id).length
    return {
      ...category,
      eventCount
    }
  })
})

const showCreateCategoryDialog = () => {
  isEditing.value = false
  categoryForm.value = {
    id: '',
    name: '',
    description: ''
  }
  categoryDialogVisible.value = true
}

const editCategory = (category) => {
  isEditing.value = true
  categoryForm.value = {
    id: category.id,
    name: category.name,
    description: category.description
  }
  categoryDialogVisible.value = true
}

const saveCategory = async () => {
  if (!categoryFormRef.value) return
  
  await categoryFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        if (isEditing.value) {
          await store.dispatch('updateCategory', { 
            id: categoryForm.value.id, 
            category: categoryForm.value 
          })
          ElMessage.success('更新分类成功')
        } else {
          const newCategory = {
            ...categoryForm.value,
            id: `category_${Date.now()}`,
            createTime: new Date().toLocaleString()
          }
          await store.dispatch('createCategory', newCategory)
          ElMessage.success('创建分类成功')
        }
        categoryDialogVisible.value = false
      } catch (error) {
        ElMessage.error(isEditing.value ? '更新分类失败' : '创建分类失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

const confirmDeleteCategory = (id) => {
  // 检查该分类下是否有事件
  const eventCount = store.state.events.filter(event => event.categoryId === id).length
  
  if (eventCount > 0) {
    ElMessage.warning(`该分类下有 ${eventCount} 个事件，无法删除`)
    return
  }
  
  ElMessageBox.confirm('确认删除该分类？此操作不可恢复！', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await store.dispatch('deleteCategory', id)
      ElMessage.success('删除成功')
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

onMounted(async () => {
  loading.value = true
  try {
    await store.dispatch('fetchCategories')
    await store.dispatch('fetchEvents')
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 